package com.smarthospital.service.impl;

import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.Cached;
import com.google.common.collect.Lists;
import com.smarthospital.common.util.SHJSONUtil;
import com.smarthospital.contants.JetCacheNames;
import com.smarthospital.contants.SHConst;
import com.smarthospital.dao.daoService.SHDictionaryDaoService;
import com.smarthospital.entity.pojo.SHDictionary;
import com.smarthospital.entity.pojo.User;
import com.smarthospital.service.CommonService;
import com.smarthospital.service.OptService;
import com.smarthospital.web.inteceptor.LoginInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * create by sym  2021/5/4 15:11.
 */
@Slf4j
@Service
public class CommonServiceImpl implements CommonService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private OptService optService;
    @Autowired
    private SHDictionaryDaoService shDictionaryDaoService;

    /**
     * 发送短信验证码
     * @param sceneType
     * @param phone
     */
    @Override
    public void optSend(Integer sceneType, String phone) throws Exception {
        //生成验证码
        Random random = new Random(10000);
        int code = random.nextInt(10000);
        //发送短信
        optService.send(code,phone);

        //将短信验证码存起来 60秒
        User user = LoginInterceptor.getUser();
        String key = String.format(SHConst.redis_key.bus_optSend,user.getId(),sceneType,phone) ;
        redisTemplate.opsForValue().set(key,code+"",60L,TimeUnit.SECONDS);
    }

    @Cached(name = JetCacheNames.dictionaryMap ,key = "#dictionary", cacheType =CacheType.BOTH,timeUnit = TimeUnit.SECONDS,expire = 120)
    @Override
    public Map dictionaryMap(String dictionary) {
        String[] split = dictionary.split(",");
        if (split.length == 1) {
            List<SHDictionary> shDictionaries = shDictionaryDaoService.queryBydictionaryCode(dictionary);
            Map map = new HashMap(1);
            map.put(dictionary,SHJSONUtil.DictionaryToMap(shDictionaries));
            return map;
        }else {
            List<String> strings = Lists.newArrayList(split);
            List<SHDictionary> shDictionaries = shDictionaryDaoService.queryIndictionaryCode(strings);
            Map<String, List<SHDictionary>> collect = shDictionaries.stream().collect(Collectors.groupingBy(SHDictionary::getDictionary));
            Map map = new HashMap(collect.size());
            for (Map.Entry<String, List<SHDictionary>> entry : collect.entrySet()) {
                map.put(entry.getKey(),SHJSONUtil.DictionaryToMap(entry.getValue()));
            }
            return map;
        }

    }


}
